'use client'
import React, { useState } from 'react';
import { Button } from './ui/button';
import { Textarea } from './ui/textarea';
import { createComment } from '../services/commentService';
import { CommentFormData } from '../types/comment';
import { AlertCircle } from 'lucide-react';

import { Comment } from '../types/comment';

interface CommentFormProps {
  articleId: string;
  onCommentCreated: (comment: Comment) => void;
}

export default function CommentForm({ articleId, onCommentCreated }: CommentFormProps) {
  const [content, setContent] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');
  
  // 检查用户是否已登录
  const isLoggedIn = !!localStorage.getItem('auth_token');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!isLoggedIn) {
      setError('请先登录再发表评论');
      return;
    }
    
    if (!content.trim()) {
      setError('评论内容不能为空');
      return;
    }
    
    if (content.trim().length < 5) {
      setError('评论内容至少需要5个字符');
      return;
    }
    
    setIsSubmitting(true);
    setError('');
    
    try {
      const commentData: CommentFormData = { articleId, content: content.trim() };
      const newComment = await createComment(articleId, commentData);
      
      // 重置表单
      setContent('');
      
      // 通知父组件评论已创建，并传递新评论数据
      onCommentCreated(newComment);
    } catch (err) {
      setError('发表评论失败，请稍后重试');
      console.error('评论提交失败:', err);
    } finally {
      setIsSubmitting(false);
    }
  };


  return (
    <div className="bg-white p-6 rounded-lg shadow-sm mb-8">
      <h3 className="text-xl font-semibold mb-4">发表评论</h3>
      
      {!isLoggedIn ? (
        <div className="flex items-center justify-center py-8">
          <p className="mr-4 text-gray-600">需要登录才能发表评论，请先登录。</p>
        </div>
      ) : (
        <form onSubmit={handleSubmit}>
          {error && (
            <div className="flex items-center gap-2 mb-4 p-3 bg-red-50 text-red-600 rounded-md">
              <AlertCircle className="w-4 h-4" />
              <span>{error}</span>
            </div>
          )}
          
          <div className="mb-4">
            <Textarea
              placeholder="写下您的评论..."
              className="w-full min-h-[120px] resize-y border-gray-200 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 outline-none"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              disabled={isSubmitting}
            />
          </div>
          
          <div className="flex justify-between items-center">
            <span className="text-sm text-gray-500">
              还可以输入 {500 - content.length} 个字符
            </span>
            
            <Button 
              type="submit" 
              disabled={isSubmitting || content.trim().length < 5}
              className="bg-blue-600 hover:bg-blue-700"
            >
              {isSubmitting ? '发表中...' : '发表评论'}
            </Button>
          </div>
        </form>
      )}
    </div>
  );
}